<template >
  <div class="login">
    <div class="login-box">
      <div class="form-box">
        <div class="avatar">
          <img src="@/assets/logo.png" alt="" />
        </div>
        <el-form :model="ruleForm" :rules="rules" ref="ruleForm" class="demo-ruleForm">
          <el-form-item prop="username">
            <el-input prefix-icon="el-icon-user-solid" v-model="ruleForm.username"></el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input prefix-icon="el-icon-lock" type="password" v-model="ruleForm.password"></el-input>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="submitForm('ruleForm')">登录</el-button>
            <el-button @click="resetForm('ruleForm')">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>
<script>
import { login_api } from '@/api/index'
export default {
  data() {
    return {
      ruleForm: {
        username: 'admin',
        password: '123456',
      },

      rules: {
        name: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 7, message: '长度在 3 到 5 个字符', trigger: 'blur' },
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' },
        ],
      },
    }
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          const res = await login_api(this.ruleForm)

          if (res.data.meta.status == 200) {
            this.$message.success(res.data.meta.msg)
            // 先将token 存到本地， 再进行跳转， 不要路由守卫的时候会先判断有没有token， 那么就要判断两次才能跳转
            window.sessionStorage.setItem('token', res.data.data.token)

            this.$router.push('/home')
          } else {
            this.$message.error(res.data.meta.msg)
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
    },
  },
}
</script>


<style scoped lang = 'less'>
.login {
  width: 100%;
  height: 100%;
  background-color: #2b4b6b;
}
.login-box {
  position: absolute;
  width: 450px;
  height: 300px;
  border-radius: 3px;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background-color: #fff;
  .form-box {
    margin-top: 100px;
    padding: 0 20px;
    .el-form-item {
      text-align: right;
    }
    .avatar {
      overflow: hidden;
      position: absolute;
      top: -20%;
      left: 50%;
      transform: translate(-50%, 0);
      width: 130px;
      height: 130px;
      background-color: #eeeeee;
      border: 10px solid #fff;
      border-radius: 50%;
      box-shadow: 0 0 5px 5px #ccc;
      img {
        width: 100;
        height: 100%;
      }
    }
  }
}
</style>